package com.feng.util;

import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;

/**
 * redis工具类
 * @author qf
 *
 */
@Configuration
public class RedisUtils {

	@Value("${userSession.timout}")
	private long timout;
	@Autowired
	private  StringRedisTemplate stringRedisTemplate;
	
	public  void setString(String key,String value) {
		stringRedisTemplate.opsForValue().set(key, value);
	}
	
	public  String getString(String key){
		return stringRedisTemplate.opsForValue().get(key);
	}
	
	/**
	 * setString带失效时间（秒）
	 * @param key
	 * @param value
	 * @param timeout	秒
	 */
	public void setString(String key,String value,long timeout) {
		stringRedisTemplate.opsForValue().set(key, value, timeout, TimeUnit.SECONDS);
	}
	
	/**
	 * 判断是否存在key
	 * @param key
	 * @return
	 */
	public Boolean hasKey(String key) {
		return stringRedisTemplate.hasKey(key);
	}
	
	/**
	 * 原有key上追加
	 * @param key
	 * @param value
	 * @return
	 */
	public Integer append(String key,String value) {
		return stringRedisTemplate.opsForValue().append(key, value);
	}
	
	/**
	 * 截取key对应的字符串
	 * @param key
	 * @param start
	 * @param end
	 * @return
	 */
	public String get(String key,long start,long end) {
		return stringRedisTemplate.opsForValue()
				.get(key, start, end);
	}
	
	/**
	 * 获取key对应的长度
	 * @param key
	 * @return
	 */
	public long getStringSize(String key) {
		return stringRedisTemplate.opsForValue().size(key);
	}
	
	
	/**
	 * 存放hashMap
	 * @param key
	 * @param hashKey
	 * @param value
	 */
	public void setHashMap(String key,String hashKey,Object value) {
		stringRedisTemplate.opsForHash().put(key, hashKey, value);
	}
	/**
	 * 存list值从左到右顺序存放
	 * @param key
	 * @param value
	 */
	public long setListLpush(String key,String value) {
		return stringRedisTemplate.opsForList().leftPush(key, value);
	}
	
	/**
	 * 存list从右到左
	 * @param key
	 * @param value
	 * @return
	 */
	public long setListRpush(String key,String value) {
		return stringRedisTemplate.opsForList().rightPush(key, value);
	}
	/**
	 * 获取list长度
	 * @param key
	 * @return
	 */
	public long getListLen(String key) {
		return stringRedisTemplate.opsForList().size(key);
	}
	
}
